from dataclasses import dataclass
from typing import Dict, Any, Callable
from halo import Halo

@dataclass
class Tool:
    name: str
    description: str
    parameters: Dict[str, Dict[str, Any]]
    example: str = ""
    timeout: int = 30
    execute_func: Callable = None  # 添加执行函数属性

    def to_xml_docs(self) -> str:
        doc = f'''
## {self.name}
描述: {self.description}
参数:
'''
        for param_name, param_info in self.parameters.items():
            doc += f"- {param_name}: ({param_info['type']}) {param_info.get('description', '')}\n"
        
        if self.example:
            doc += f"\n示例:\n{self.example}\n"
        
        return doc

    def execute(self, params: dict) -> str:
        """执行工具"""
        if not self.execute_func:
            return "错误：工具未设置执行函数"
        return self.execute_func(params)

TOOLS = {}

def execute_tool(tool_name: str, params: dict) -> str:
    """执行工具并显示加载动画"""
    if tool_name not in TOOLS:
        return f"错误：未找到工具 {tool_name}"
        
    spinner = Halo(text=f"执行 {tool_name}", spinner='dots')
    try:
        spinner.start()
        result = TOOLS[tool_name].execute(params)
        spinner.succeed(f"完成 {tool_name}")
        return result
    except Exception as e:
        spinner.fail(f"执行失败 {tool_name}")
        return f"执行出错：{str(e)}"
    finally:
        if spinner.spinner_id:
            spinner.stop()